
//获取应用实例
// const innerAudioContext = wx.createInnerAudioContext();
const app = getApp();
const recorderManager = wx.getRecorderManager();
// const recorderManager = app.globalData.recorderManager;
var storage = require('../../utils/storage.js');
var util = require('../../utils/util.js');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    content: '',
    countDownShow: false,
    lyricShow: false,
    audioShow: false,
    isOpen: true, //播放开关
    starttime: "00:00", //正在播放时长
    duration: "10:00", //总时长
    src: "",
    objectid: "",
    init: true,
    isPause: true,
    count: 0,
    coverObjectid: '',
    max: 600,//进度条最大值
    three: "",
    showLeftAndRight: false,//录音时不展示重录和保存，暂时和结束时显示

    openRecordingdis: "block",//录音图片的不同
    shutRecordingdis: "none",//录音图片的不同
    recordingTimeqwe:0,//录音计时
    setInter:""//录音名称

    
  },
 
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    //屏蔽右上角分享功能
    wx.hideShareMenu();
    console.log(options);
    var activityId = options.activityId;
    var cover = options.cover;
    this.setData({
      activityId: activityId,
      cover: cover
    })
    
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    clearInterval(this.data.setInter);
    clearInterval(this.data.three);
    //停止录音 计时器也要停止
    recorderManager.stop();
    recorderManager.onStop((res) => {
      //不做处理
    })
    
    //恢复默认属性值
    this.setData({
      countDownShow: false,
      lyricShow: false,
      audioShow: false,
      isOpen: true, //播放开关
      starttime: "00:00", //正在播放时长
      duration: "10:00", //总时长
      init: true,
      isPause: true,
      count: 0,
      max: 600,//进度条最大值
      recordingTimeqwe:0,//录音计时
      setInter: 0,//录音名称
      three: 0,
      showLeftAndRight: false
    })

    var content = storage.get('content');
    console.log("content: " + content);
    if(content != undefined && content.length > 0){
      this.setData({
        lyricShow: true,
        content: content
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    //停止录音 计时器也要停止
    // recorderManager.stop();
    // clearInterval(this.data.setInter);
    // clearInterval(this.data.three);
    // recorderManager.onStop((res) => {
    //   //不做处理
    // })
   
    // // storage.remove('content');
    // //恢复默认属性值
    // this.setData({
    //   countDownShow: false,
    //   lyricShow: false,
    //   audioShow: false,
    //   isOpen: true, //播放开关
    //   starttime: "00:00", //正在播放时长
    //   duration: "10:00", //总时长
    //   init: true,
    //   isPause: true,
    //   count: 0,
    //   max: 600,//进度条最大值
    //   recordingTimeqwe:0,//录音计时
    //   setInter: 0,//录音名称
    //   three: 0,
    //   showLeftAndRight: false
    // })
    var that = this;
    recorderManager.pause();
    recorderManager.onPause((res) => {
      console.log('暂停录音');
      that.setData({
        isOpen: false,
        showLeftAndRight: true,
        isPause: true
      });
      //计数器需要暂停
      clearInterval(that.data.setInter);
      clearInterval(that.data.three);
    })
    clearInterval(that.data.setInter);
    clearInterval(that.data.three);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    //停止录音 计时器也要停止
    // recorderManager.stop();
    // clearInterval(this.data.setInter);
    // clearInterval(this.data.three);
    // recorderManager.onStop((res) => {
    //   //不做处理
    // })
   
    // storage.remove('content');
    // //恢复默认属性值
    // this.setData({
    //   countDownShow: false,
    //   lyricShow: false,
    //   audioShow: false,
    //   isOpen: true, //播放开关
    //   starttime: "00:00", //正在播放时长
    //   duration: "10:00", //总时长
    //   init: true,
    //   isPause: true,
    //   count: 0,
    //   max: 600,//进度条最大值
    //   recordingTimeqwe:0,//录音计时
    //   setInter: 0,//录音名称
    //   three: 0,
    //   showLeftAndRight: false
    // })
    var that = this;
    recorderManager.pause();
    recorderManager.onPause((res) => {
      console.log('暂停录音');
      that.setData({
        isOpen: false,
        showLeftAndRight: true,
        isPause: true
      });
      //计数器需要暂停
      clearInterval(that.data.setInter);
      clearInterval(that.data.three);
    })
    clearInterval(that.data.setInter);
    clearInterval(that.data.three);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {},

  /**
   * 保存视频
   */
  saveVideo: function(e){
    //页面跳转
    wx.navigateTo({
      url: '/pages/readingAloud/uploadAudio/uploadAudio?objectid=' + this.data.objectid + "&temp=" + this.data.src,
    })
  },

  /**
   * 重新录制
   */
  resetVideo: function(e){
    //停止录音 计时器也要停止
    clearInterval(this.data.setInter);
    clearInterval(this.data.three);
    recorderManager.stop();
    recorderManager.onStop((res) => {
      //不做处理
    })
    
    storage.remove('content');
    //恢复默认属性值
    this.setData({
      countDownShow: false,
      lyricShow: false,
      audioShow: false,
      isOpen: true, //播放开关
      starttime: "00:00", //正在播放时长
      duration: "10:00", //总时长
      init: true,
      isPause: true,
      count: 0,
      max: 600,//进度条最大值
      recordingTimeqwe:0,//录音计时
      setInter: 0,//录音名称
      three: 0,
      showLeftAndRight: false
    })

  },

  //录音计时器
  recordingTimer:function(){
    var that = this;
  //将计时器赋值给setInter
    that.data.setInter = setInterval(
      function () {
        var time = that.data.recordingTimeqwe + 1;
        console.log(time);
        that.setData({
          recordingTimeqwe: time,
          starttime: util.formatSeconds(time)
        })
        //当达到十分钟时自动结束
        if(time == 597){
          that.shutRecording();
        }
      }
      , 1000); 
},
  
  
  //开始录音
  openRecording: function() {
    var that = this;
    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          shutRecordingdis: "block",
          openRecordingdis: "none",
          isPause: false
        })
      }
    })
    const options = {
      duration: 600000, //指定录音的时长，单位 ms，最大为10分钟（600000），默认为1分钟（60000）
      sampleRate: 16000, //采样率
      numberOfChannels: 1, //录音通道数
      encodeBitRate: 96000, //编码码率
      format: 'mp3', //音频格式，有效值 aac/mp3
      frameSize: 50, //指定帧大小，单位 KB
    }
    //TODO 需要倒计时三秒开始
    that.data.three = setInterval(
      function () {
        var count = that.data.count + 1;
        that.setData({
          count: count,
          countDownShow: true  
        })
        
        if(count == 4){    
          that.setData({
            init: false
          })     
          //开始录音
          recorderManager.start(options);
          //开始录音计时   
          that.recordingTimer();
          recorderManager.onStart(() => {
            console.log('。。。开始录音。。。');
            
          });
          //监听录音中断 add at 2020-04-13
          
          //错误回调
          recorderManager.onError((res) => {
            console.log(res);

          })
          clearInterval(that.data.three);
        }
      }
      , 1000); 
  
  },

  //结束录音
  shutRecording: function() {
    wx.showLoading({
      title: '保存中',
    })
    var that = this;
    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          shutRecordingdis: "none",
          openRecordingdis: "block",
          showLeftAndRight: true,
          isPause: true
        })
      }
    })
    recorderManager.stop();
    clearInterval(that.data.setInter);
    clearInterval(that.data.three);
    console.log("停止录音和计数器完成");
    recorderManager.onStop((res) => {
      console.log('。。停止录音。。', res.tempFilePath)
      const {tempFilePath} = res;
      //结束录音计时  
      // clearInterval(that.data.setInter);
      //上传录音
      var objectid = "";
      wx.uploadFile({
        url: 'https://wxgt.chaoxing.com/wechat/uploadfile',//服务器接口
        filePath: tempFilePath,
        name:"file",//后台要绑定的名称
        header: {
          "Content-Type": "multipart/form-data"
        },
        success:function(res){
          console.log(res);
          var data = JSON.parse(res.data);
          if(data.code == 200){
            console.log('上传成功');
            objectid = data.data.objectid;
            console.log("objectid: " + objectid);
          }else{
            console.log('接口调用失败');             
          }
          wx.hideLoading();
          //TODO 跳转到音频操作页面
          wx.navigateTo({
            url: '/pages/readingAloud/uploadAudio/uploadAudio?objectid=' + objectid + "&temp=" + tempFilePath + "&activityId=" + that.data.activityId + "&cover=" + that.data.cover,
          })
        },
        fail: function(res){
          console.log("。。录音保存失败。。");
          wx.hideLoading();
        }
      })      
  })
},

// 暂停录音
pause: function() {
  var that = this;
  recorderManager.pause();
  recorderManager.onPause((res) => {
    console.log('暂停录音');
    that.setData({
      isOpen: false,
      showLeftAndRight: true,
      isPause: true
    });
    //计数器需要暂停
    clearInterval(that.data.setInter);
    clearInterval(that.data.three);
  })
  clearInterval(that.data.setInter);
  clearInterval(that.data.three);
},

//继续录音
continue: function() {
  var that = this;
  console.log("继续录音");
  that.setData({
    isOpen: true,
    showLeftAndRight: false,
    isPause: false
  })
  recorderManager.resume();
  recorderManager.onResume((res) => {
    
  })
  //开始计时
  that.recordingTimer();

  
},

/**
 * 跳转到添加朗读内容页面
 */
addContent: function(e){
  console.log(e);
  // if(this.data.count == 0){
  if(this.data.isPause){
    wx.navigateTo({
      url: '/pages/readingAloud/addReadContent/addReadContent',
    })
  }
  
},

});
